/*
 * IntelliJ IDEA: .
 * Copyright 2014 Ifoly.inc. All right reserved.
 *
 * path:
 * author: liuhui
 * version: 1.0.0
 */
define(function (require, exports, module) {
    var Product;
    $('body').addClass('page-sidebar-closed');
    $('.page-sidebar-menu').addClass('page-sidebar-menu-closed');

    var action_hbs = require('hbs!./product/action');
    var href_hbs = require('hbs!./common/list_href');

    // 初始化
    var dt = new Datatable();

    Product = function () {

        function initDT() {
            dt.init({
                src      : $("#product_dt"),
                onSuccess: function (grid) {
                },
                onError  : function (grid) {
                },
                loadingMessage: '加载中...',
                dataTable: {
                    columns   : [{
                        data: 'id'
                    }, {
                        data: 'code'
                    }, {
                        data: 'name'
                    }, {
                        data: 'price'
                    }, {
                        data: 'time_limit'
                    }, {
                        data: 'valuedate_offset'
                    }, {
                        data: 'time_limit_unit'
                    }, {
                        data: 'risk_tolerance'
                    }, {
                        data: 'progress'
                    }, {
                        data: 'publish_time'
                    }, {
                        data: 'creater_name'
                    }, {
                        data: 'status'
                    }, {
                        data: 'recommend'
                    }, {
                        data: null
                    }],
                    columnDefs: [
                        {'visible': false, targets: [0, 6, 12]},
                        {
                            targets: 1,
                            render: function (data, type, full, meta) {
                                return href_hbs({
                                    href_value: g.ctx + 'product/detail_view/'+full['id'],
                                    dis_name:data
                                })
                            }
                        },
                        {
                            targets: 11,
                            render: function (data, type, full, meta) {
                                return constantsStatus.product[data];
                            }
                        },
                        {
                            targets: 4,
                            render: function (data, type, full, meta) {
                                return '{0}{1}'.format(data, (full['time_limit_unit'] == 'day' ? '天' : '月'));
                            }
                        },
                        {
                            targets: 5,
                            render: function (data, type, full, meta) {
                                return '<span class="label label-primary">T+{0}</span>'.format(data);
                            }
                        },
                        {
                            targets: 7,
                            render: function (data, type, full, meta) {
                                return constantsStatus.risklevel[data];
                            }
                        },
                        {
                            targets: 8,
                            render: function (data, type, full, meta) {
                                return data + '%';
                            }
                        },
                        DTKit.renderActionColumn(function (data, type, full, row) {
                            full['ctx'] = g.ctx;
                            full['recommend'] = full['recommend'] == "Y";
                            var status = full['status'];
                            full['readystatus'] = status == 0;

                            full["product_edit"] = product_edit == 1;
                            full["product_clearing_time"] = product_clearing_time == 1;
                            full["product_recommended"] = product_recommended == 1 && status != 3 && status != 0;
                            full["product_intro"] = product_intro == 1;
                            full["product_remove"] = product_remove == 1;
                            full["product_fail"] = (status == 1 || status == 2 || status == 7);
                            return action_hbs(full);
                        })
                    ],
                    "order"   : [
                        [9, "desc"]
                    ]
                }
            });
        }

        function bindEvents() {
            // 查询
            $('#search_btn').click(function (e) {
                dt.setAjaxParam("multiquery", "1");
                dt.setAjaxParam("s-name-like", $('#s_product_name').val());
                dt.setAjaxParam("s-status", $('#s_status').val());
                dt.setAjaxParam("s-code-like", $('#p_code').val());
                dt.setAjaxParam("s-creater_name-like", $('#s_creater_name').val());
                dt.setAjaxParam("s-type", $('#p_type').val());
                //年利化率
                dt.setAjaxParam("p_yield_start", $('#p_yield_start').val());
                dt.setAjaxParam("p_yield_end", $('#p_yield_end').val());
                //起息日
                dt.setAjaxParam("p_due_date_start", $('#p_due_date_start').val());
                dt.setAjaxParam("p_due_date_end", $('#p_due_date_end').val());
                //项目本金
                dt.setAjaxParam("p_price_start", $('#p_price_start').val());
                dt.setAjaxParam("p_price_end", $('#p_price_end').val());
                //起投金额
                dt.setAjaxParam("p_min_invest_amount_start", $('#p_min_invest_amount_start').val());
                dt.setAjaxParam("p_min_invest_amount_end", $('#p_min_invest_amount_end').val());

                dt.getDataTable().ajax.reload();
            });


            var $productDt = $("#product_dt");
            $productDt.on('click', '.recommend', function (e) {
                e.preventDefault();
                var $this = $(this);
                var href_url = $this.attr("href");
                var id = $this.data("pk");
                var set_val = $this.data("value");
                bootbox.confirm("你确定要设置首页推荐吗", function (result) {
                    if (result) {
                        $.getJSON(
                            href_url,
                            {
                                id: id,
                                set_val: set_val
                            },
                            function (json) {
                                if (json.status == "OK") {
                                    bootbox.alert("设置成功");
                                    dt.getDataTable().ajax.reload();
                                } else {
                                    bootbox.alert(json.message);
                                }
                            }
                        );
                    }
                });
                return false;
            });
            $productDt.on('click', '.onoff', function (e) {
                e.preventDefault();
                var $this = $(this);
                var id = $this.data("pk");
                var status_url = $this.attr("href");
                var set_val = $this.data("value");

                bootbox.confirm("你确定要执行该操作吗", function (result) {
                    if (result) {
                        $.getJSON(
                            status_url,
                            {
                                id: id,
                                set_val: set_val
                            },
                            function (json) {
                                if (json.status == "OK") {
                                    bootbox.alert("修改成功");
                                    dt.getDataTable().ajax.reload();
                                } else {
                                    bootbox.alert(json.message);
                                }
                            }
                        );
                    }
                });
                return false;
            });
            $productDt.on('click', '.action-edit', function (e) {
                e.preventDefault();
                var product_id = $(this).data("id");
                var href = $(this).data("href");
                var url = g.ctx + "product/editeCheck";

                $.ajax({
                    url : url,
                    data: {
                        id: product_id
                    },
                    type: "POST"
                }).done(function (msg) {
                    if (msg.status == "FAILURE") {
                        bootbox.alert(msg.message, function () {
                            window.location.href = g.ctx + "product/edit/" + product_id + '-readonly';
                        });
                    } else {
                        window.location.href = g.ctx + "product/edit/" + product_id;
                    }
                }).fail(function () {
                    bootbox.alert("error");
                    return false;
                });
                return false;
            });
            $productDt.on('click', '.action-delete', function (e) {
                e.preventDefault();
                var $2 = $(this);
                bootbox.confirm("你确定要删除吗", function (result) {
                    if (result) {
                        var product_id = $2.data("id");
                        var href = $2.data("href");
                        var url = g.ctx + "product/deleteCheck";

                        $.ajax({
                            url : url,
                            data: {
                                id: product_id
                            },
                            type: "POST"
                        }).done(function (msg) {
                            if (msg.status == "FAILURE") {
                                bootbox.alert(msg.message, function () {});
                            } else if (msg.status == "OK") {
                                $.ajax({
                                    url : href,
                                    type: "POST"
                                }).done(function (msg) {
                                    bootbox.alert(msg.message, function () {
                                        dt.getDataTable().ajax.reload();
                                    });
                                }).fail(function () {
                                    bootbox.alert("error");
                                    return false;
                                })
                            }
                        }).fail(function () {
                            bootbox.alert("error");
                            return false;
                        })
                    }
                });
                return false;
            });
            $productDt.on('click', '.action-raisedfailure', function (e) {
                e.preventDefault();
                // 募集失败操作
                var $this = $(this);
                var href = $this.attr('href');
                bootbox.confirm("您确定要将该产品手动调整为募集失败么？", function (result) {
                    if (result) {

                        $.ajax({
                            url : href,
                            type: "POST"
                        }).done(function (msg) {
                            if (msg.status == "OK") {
                                bootbox.alert('操作成功', function () {
                                    dt.getDataTable().ajax.reload();
                                });
                            } else {
                                bootbox.alert(msg.message);
                            }
                        }).fail(function () {
                            bootbox.alert("系统发生错误");
                            return false;
                        })
                    }
                });
                return false;
            });
        }

        return {
            init: function () {
                $('#s_pubdate').daterangepicker({
                    timePicker: false,
                    timePickerIncrement: 30,
                    format: 'YYYY/MM/DD'
                });
                initDT();
                bindEvents();
            }
        };
    }();
    return {
        init: function () {
            Product.init();
        }
    };
});